<script setup lang='ts'>
import { toRefs, watch } from 'vue'

const props = defineProps<{
    data: any
}>()

const emits = defineEmits(['sortChange', 'clickHandle'])
const { data } = toRefs(props)
const items = ref<any>([])
const active = ref()

function doSort(index: number, order: string) {
    const flag = items.value[index].order === order
    if (flag)
        items.value[index].order = ''
    else
        items.value[index].order = order

    emits('sortChange', items.value[index], order)
}

function clickHandle(val: any, index: number) {
    if (active.value === index) {
        active.value = ''

        emits('clickHandle', '')
    }
    else {
        active.value = index
        emits('clickHandle', val)
    }
}

function init(val: any) {
    items.value = val.map((v: any) => {
        return {
            ...v,
            order: '',
        }
    })
}

watch(data, (val: any) => {
    init(val)
}, {
    immediate: true,
})
</script>

<template>
    <div class="text-18 c-#767676 flex cursor-pointer">
        <div v-for="(item, index) in items"
             :key="index"
             class="mr-40 relative"
        >
            <span :class="{ 'c-#DA0004': active === index }"
                  @click="clickHandle(item, index)"
            >{{ item?.label }}</span>

            <template v-if="item?.sort">
                <span class="sort-arrow rotate-180"
                      :class="{ 'sort-active': item.order === 'asc' }"
                      @click="doSort(index, 'asc')"
                />

                <span class="sort-arrow bottom-0"
                      :class="{ 'sort-active': item.order === 'desc' }"
                      @click="doSort(index, 'desc')"
                />
            </template>
        </div>
    </div>
</template>

<style lang="less" scoped>
.sort-arrow {
    position: absolute;
    width: 0;
    height: 0;
    border: 5px solid;
    border-color: #c9cdd4 transparent transparent;
    margin-left: 5px;
}

.sort-active {
    border-color: #da0004 transparent transparent;
}
</style>
